<template>
  <tiny-drawer :title="title" :visible="visible" width="50%" :show-footer="true" @close="onClose(false)">
    <tiny-form ref="formDataRef" class="tiny-drawer-body-form" :rules="formDataRules" :model="formData"
      label-width="110px" validate-position="bottom" validate-type="text">
      <tiny-row>
        <tiny-col :span="6">
          <tiny-form-item :label="$t('system.msg-template.name')" prop="name">
            <tiny-input v-model="formData.name" :placeholder="$t('system.msg-template.name.placeholder')"></tiny-input>
          </tiny-form-item>
        </tiny-col>
        <tiny-col :span="6">
          <tiny-form-item :label="$t('system.msg-template.templateCode')" prop="templateCode">
            <tiny-input v-model="formData.templateCode"
              :placeholder="$t('system.msg-template.templateCode.placeholder')"></tiny-input>
          </tiny-form-item>
        </tiny-col>
      </tiny-row>
      <tiny-form-item :label="$t('attribute.remark')" prop="remark">
        <tiny-input v-model="formData.remark" :placeholder="$t('attribute.remark.placeholder')" type="textarea"
          :maxlength="500" :rows="5" show-word-limit>
        </tiny-input>
      </tiny-form-item>

      <tiny-collapse v-model="activeNames">
        <tiny-collapse-item title="站内消息" v-for="(item, index) in formData.channelList" :key="index"
          :name="item.channel">
          <template #title-right>
            <tiny-switch v-model="item.enabled"></tiny-switch>
          </template>
          <tiny-form-item :label="$t('system.msg-template.titleTemplate')" prop="titleTemplate">
            <tiny-input v-model="item.titleTemplate"
              :placeholder="$t('system.msg-template.titleTemplate.placeholder')"></tiny-input>
          </tiny-form-item>
          <tiny-form-item :label="$t('system.msg-template.contentTemplate')" prop="contentTemplate">
            <div style="border: 1px solid #c2c2c2; ">
              <Toolbar :editor="editorRef" :defaultConfig="toolbarConfig" mode="simple"
                style="border-bottom: 1px solid #c2c2c2;" />
              <Editor style="height: 200px; overflow-y: hidden;" v-model="item.contentTemplate" :defaultConfig="editorConfig"
                @onCreated="handleCreated" mode="simple" />
            </div>

          </tiny-form-item>
        </tiny-collapse-item>
      </tiny-collapse>
    </tiny-form>

    <template #footer>
      <tiny-button type="primary" @click="onSubmit">保存</tiny-button>
      <tiny-button @click="onClose(false)">取消</tiny-button>
    </template>
  </tiny-drawer>
</template>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<script lang="ts" setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css

import * as MsgTemplateApi from '@/api/system/msg/template';
import * as MsgChannelApi from '@/api/system/msg/channel';
import { computed, getCurrentInstance, ref, toRaw, shallowRef, onBeforeUnmount } from 'vue';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'


const { proxy } = getCurrentInstance() as any;

const emit = defineEmits(['ok']);

const visible = ref(false);
const isModify = ref(false);
const title = computed(() => {
  return isModify.value ? '修改消息模板' : '新增消息模板';
});

const editorRef = shallowRef()
const toolbarConfig = ref({
  excludeKeys: [
    'emotion',
    'group-image',
    'group-link',
    'insertLink',
    'insertVideo',
    'group-video',
    'codeBlock',
    'undo',
    'redo',
    'divider',
    'bgColor',
    'insertTable',
  ]
})
const editorConfig = { placeholder: '请输入内容...' }

onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor: any) => {
  editorRef.value = editor
}


const activeNames = ref(['WEB']);

const formData = ref<MsgTemplateApi.TemplateVO>({});

const init = () => {
  formData.value = {
    channelList: [
      {
        channel: 'WEB',
      },
    ],
  }
}

const formDataRules = {
  name: [{ required: true, message: '消息模板名称不能为空', trigger: 'change' }],
  templateCode: [{ required: true, message: '消息模板编码不能为空', trigger: 'change' }],
  msgType: [{ required: true, message: '消息类型不能为空', trigger: 'change' }],
};

const onSubmit = () => {
  proxy.$refs.formDataRef.validate((valid: boolean) => {
    if (valid) {
      if (formData.value.id) {
        MsgTemplateApi.updateTemplateById(formData.value.id, toRaw(formData.value)).then(
          () => {
            proxy.$modal.message({ message: '修改成功', status: 'success' });
            onClose(true);
          },
        );
      } else {
        MsgTemplateApi.addTemplate(toRaw(formData.value)).then(() => {
          proxy.$modal.message({ message: '创建成功', status: 'success' });
          onClose(true);
        });
      }
    }
  });
};

const onClose = (refresh?: boolean) => {
  visible.value = false;
  if (refresh) {
    emit('ok');
  }
};

const open = (id: string) => {
  isModify.value = false;
  proxy.$refs.formDataRef.resetFields();
  init()
  if (id) {
    MsgTemplateApi.getTemplateDetailById(id).then((response) => {
      formData.value = response.data;
      isModify.value = true;
    });
  }
  visible.value = true;
};
defineExpose({
  open,
});
</script>
